from datetime import datetime
import os
from flask import Blueprint, render_template, redirect, url_for, flash, request, send_from_directory, current_app, abort
from flask_login import login_required, current_user
from werkzeug.utils import secure_filename
from app import db
from app.models import PDFFile
from app.forms import UploadPDFForm
import uuid

main = Blueprint('main', __name__)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() == 'pdf'

@main.route('/')
@main.route('/index')
@login_required
def index():
    page = request.args.get('page', 1, type=int)
    tag = request.args.get('tag')
    
    query = PDFFile.query
    if tag:
        query = query.filter(PDFFile.tags.contains(tag))
    
    files = query.order_by(PDFFile.upload_date.desc()).paginate(
        page=page, per_page=10, error_out=False)
    return render_template('index.html', files=files)

@main.route('/upload', methods=['GET', 'POST'])
@login_required
def upload():
    if not current_user.is_admin:
        flash('Only administrators can upload files.')
        return redirect(url_for('main.index'))
        
    form = UploadPDFForm()
    if form.validate_on_submit():
        file = form.file.data
        if file and allowed_file(file.filename):
            # 保存原始文件名（包括中文）
            original_filename = file.filename
            
            # 生成唯一的存储文件名
            file_extension = os.path.splitext(original_filename)[1]
            current_time = datetime.now()
            unique_filename = f"{current_time.strftime('%Y%m%d_%H%M%S')}_{str(uuid.uuid4())[:8]}{file_extension}"
            
            # 保存文件
            file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], unique_filename)
            file.save(file_path)
            
            # 获取文件大小
            file_size = os.path.getsize(file_path)
            
            # 创建数据库记录，使用本地时间
            pdf_file = PDFFile(
                filename=unique_filename,
                original_filename=original_filename,
                file_size=file_size,
                uploader_id=current_user.id,
                upload_date=current_time  # 使用本地时间
            )
            
            if form.tags.data:
                pdf_file.tags = form.tags.data
            
            db.session.add(pdf_file)
            db.session.commit()
            
            flash('File successfully uploaded!')
            return redirect(url_for('main.index'))
        else:
            flash('Invalid file type. Please upload PDF files only.')
            
    return render_template('upload.html', form=form)

@main.route('/view/<filename>')
@login_required
def view_file(filename):
    pdf_file = PDFFile.query.filter_by(filename=filename).first_or_404()
    return render_template('view_pdf.html', filename=filename, file=pdf_file)

@main.route('/get_pdf/<filename>')
@login_required
def get_pdf(filename):
    try:
        pdf_file = PDFFile.query.filter_by(filename=filename).first_or_404()
        return send_from_directory(current_app.config['UPLOAD_FOLDER'], filename)
    except FileNotFoundError:
        abort(404)

@main.route('/download/<filename>')
@login_required
def download_file(filename):
    try:
        pdf_file = PDFFile.query.filter_by(filename=filename).first_or_404()
        return send_from_directory(
            current_app.config['UPLOAD_FOLDER'],
            filename,
            as_attachment=True,
            download_name=pdf_file.original_filename
        )
    except FileNotFoundError:
        abort(404)

@main.route('/delete/<int:file_id>')
@login_required
def delete_file(file_id):
    if not current_user.is_admin:
        flash('Only administrators can delete files.')
        return redirect(url_for('main.index'))
        
    pdf_file = PDFFile.query.get_or_404(file_id)
    file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], pdf_file.filename)
    
    if os.path.exists(file_path):
        os.remove(file_path)
    
    db.session.delete(pdf_file)
    db.session.commit()
    
    flash('File successfully deleted.')
    return redirect(url_for('main.index'))
